package com.hss.thread.wait;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * https://www.cnblogs.com/zl1991/p/6930160.html
 */
public class WaitThread_Executor {
    private static final int TOTAL_THREADS = 10;
    private final CountDownLatch mDoneSignal = new CountDownLatch(TOTAL_THREADS);

    class RunnableWorker implements Runnable {
        private final CountDownLatch mDoneSignal;
        private final int mThreadIndex;
        Random random = new Random();

        public RunnableWorker(CountDownLatch mDoneSignal, int mThreadIndex) {
            this.mDoneSignal = mDoneSignal;
            this.mThreadIndex = mThreadIndex;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(random.nextInt(100));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread " + mThreadIndex + " Done Now:" + System.currentTimeMillis());
            mDoneSignal.countDown();
            try {
                Thread.sleep(5000);
                System.out.println("Thread " + mThreadIndex + " Do something else after notifing main thread");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    void doPrepareWork() {
        System.out.println("Ready,GO!");
    }

    void doSomethingElse() {
//        for (int i = 0; i < 100000; i++) {
//        }
        System.out.println("Main Thread Do something else.");
    }

    void main() {
        System.out.println("Main Thread Now:" + System.currentTimeMillis());
        doPrepareWork();
        Executor executor = Executors.newFixedThreadPool(TOTAL_THREADS);
        for (int i = 0; i < TOTAL_THREADS; i++) {
            executor.execute(new RunnableWorker(mDoneSignal, i));
        }
        doSomethingElse();// 做点自己的事情
        try {
            mDoneSignal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("All workers have finished now.");
         System.out.println("Main Thread Now:" + System.currentTimeMillis());
    }

    public static void main(String[] args) {
        new WaitThread_Executor().main();
    }
}
